﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.IO;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;

namespace UnionPay4WP
{
    public class UPPayHttpRequest
    {
        //private string url="";
       // public string Url { set { url = value; } get { return url; } }

        private string xmlRequest = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<cupMobiles>
	<cupMobile application=""UPNoCard"" version=""1.01"">
		<transaction type=""BankSupportEnquiry.APReq"">
			<sessionID>a6bfa12afa0a4fb19564012e02228556</sessionID>
		</transaction>
	</cupMobile>
</cupMobiles>
";


        /// <summary>
        /// 异步Post请求
        /// </summary>
        public void HttpPost(string url,string xml )
        {

            try
            {
                //请求地址
                //textBlockMsg.Text = "获取中..."; 


                //创建WebRequest类
                HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(url));
                xmlRequest=xml;

                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(myUrl));
                request.Method = "POST";
                request.ContentType = "application/xml";
                request.Accept = "application/xml";

                request.BeginGetRequestStream(requestCallback, request);
            }
            catch (WebException e)
            {
                //MessageBox.Show(e.Message);
                //textBlockMsg.Text = "网络异常，稍后再试...";
                //网络相关异常处理 
            }
            catch //(Exception e)
            {
                //异常处理
                // MessageBox.Show(e.Message);
            }
        }
        /// <summary>
        /// 发送异步Post请求
        /// </summary>
        /// <param name="result"></param>
        private void requestCallback(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(xmlRequest);
                Stream postStream = request.EndGetRequestStream(result);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                postStream.Dispose();
                //返回应答请求异步操作的状态
                request.BeginGetResponse(responseCallback, request);
            }
            catch { }
        }

        /// <summary>
        /// 异步获取Post的相应流
        /// </summary>
        /// <param name="result"></param>
        private void responseCallback(IAsyncResult result)
        {
            try
            {
                //获取异步操作返回的的信息
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                //解析应答头
                //parseRecvHeader(response.Headers);
                //获取请求体信息长度
                long contentLength = response.ContentLength;
                //获取应答码
                int statusCode = (int)response.StatusCode;
                string statusText = response.StatusDescription;
               // string nextUri = null;
                int nextUri = 0;////////////
                //应答头信息验证
                using (Stream stream = response.GetResponseStream())
                {
                    //获取请求信息
                    try
                    {
                        StreamReader read = new StreamReader(stream);
                        string msg = read.ReadToEnd();
                        //ToDo xml parsor(正常处理，异常情况)
                        XmlResponseParser xmlParser = new XmlResponseParser();
                        if (xmlParser.parse(msg,out nextUri))
                        {
                            //todo 取消暗影ui，跳转下一页
                           // PhoneApplicationPage page=Application.Current as MainPage;

                         //   UnionPayControl upc = Application.Current as UnionPayControl;
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                            //    UnionPayControl.popup.IsOpen = false;
                            //    UnionPayControl.pivot.selectedItem = Convert.ToInt32(nextUri);
                               // MainPage page = App.Current.RootVisual. as MainPage;//((PhoneApplicationPage)Application.Current).RootFrame.Content as MainPage;
                               // SelectCard page = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as SelectCard;
                              
                            });
                            
                        }
                        else
                        {
                            //todo 暗影ui，跳转。？
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                              //  UnionPayControl.popup.IsOpen = false;
                                
                              //  UnionPayControl.NavigateToError(ServerResponseVars.TransResponseCode);
                              
                            });
                        }
                        ;
                    }
                    catch (Exception e)
                    {
                    }

                }

            }
            catch (WebException e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //textBlockMsg.Text = "网络异常，稍后再试...";
                });
                // MessageBox.Show(e.Message);
                //连接失败
            }
            catch
            {
                //MessageBox.Show(e.Message);
                //异常处理
            }
        }


        //public string Xmlbuilder

    }
}
